package nuc.ss.wl.dao.impl;

import nuc.ss.wl.dao.CCDao;
import nuc.ss.wl.entity.CC;
import nuc.ss.wl.entity.SC;
import nuc.ss.wl.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CCDaoImpl implements CCDao {
    @Override
    public int save(CC cc) {
        String sql = "insert into CC values(?, ?, ?)";
        Object[] params = {
                cc.getClassno(),
                cc.getCno(),
                cc.getTno()
        };
        return DBUtil.executeUpdate(sql, params);
    }

    @Override
    public int delete(int classno, int cno) {
        String sql = "delete from CC where classno = ? and cno = ?";
        Object[] params = {
                classno,
                cno
        };
        return DBUtil.executeUpdate(sql, params);
    }

    @Override
    public int update(CC cc) {
        String sql = "update SC set tno = ? where classno = ? and cno = ?";
        Object[] params = {
                cc.getTno(),
                cc.getClassno(),
                cc.getCno()
        };
        return DBUtil.executeUpdate(sql, params);
    }

    @Override
    public List<CC> findAll() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        CC cc = null;
        List<CC> ccList = new ArrayList<>();
        conn = DBUtil.getConnection();
        String sql = "select * from CC";
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                cc = new CC(rs.getInt(1), rs.getInt(2), rs.getInt(3));
                ccList.add(cc);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, ps, conn);
        }
        return ccList;
    }

    @Override
    public CC findByClassnoAndCno(int classno, int cno) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        CC cc = null;
        conn = DBUtil.getConnection();
        String sql = "select * from CC where classno = ? and cno = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, classno);
            ps.setInt(2, cno);
            rs = ps.executeQuery();
            while (rs.next()) {
                cc = new CC(rs.getInt(1), rs.getInt(2), rs.getInt(3));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, ps, conn);
        }
        return cc;
    }
}
